//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package org_dao

import (
	"context"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"atomgit.com/openlinksaas/proto-gen-go.git/org_asset_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type AssetCateInfoDbItem struct {
	AssetCateId string `bson:"_id"`
	OrgId       string `bson:"orgId"`
	CateName    string `bson:"cateName"`
	AssetCount  uint32 `bson:"assetCount"`
	TimeStamp   int64  `bson:"timeStamp"`
}

func (item *AssetCateInfoDbItem) ToAssetCateInfo() *org_asset_api.AssetCateInfo {
	return &org_asset_api.AssetCateInfo{
		AssetCateId: item.AssetCateId,
		CateName:    item.CateName,
		AssetCount:  item.AssetCount,
	}
}

type _AssetCateDao struct {
	mc *mongo.Collection
}

func newAssetCateDao(db *mongo.Database) (*_AssetCateDao, error) {
	mc := db.Collection(db_ns.DB_NS_ORG + "asset_cate")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"orgId", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_AssetCateDao{mc: mc}, nil
}

func (db *_AssetCateDao) Insert(ctx context.Context, dbItem *AssetCateInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_AssetCateDao) Get(ctx context.Context, orgId, assetCateId string) (*AssetCateInfoDbItem, error) {
	retItem := &AssetCateInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": assetCateId, "orgId": orgId}).Decode(retItem)
	return retItem, err
}

func (db *_AssetCateDao) Exist(ctx context.Context, orgId, assetCateId string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": assetCateId, "orgId": orgId})
	return count > 0, err
}

func (db *_AssetCateDao) Remove(ctx context.Context, orgId, assetCateId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": assetCateId, "orgId": orgId})
	return err
}

func (db *_AssetCateDao) RemoveByOrg(ctx context.Context, orgId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"orgId": orgId})
	return err
}

func (db *_AssetCateDao) List(ctx context.Context, orgId string) ([]*AssetCateInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"orgId": orgId}, options.Find().SetSort(bson.M{"timeStamp": -1}))
	if err != nil {
		return nil, err
	}

	retList := []*AssetCateInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_AssetCateDao) UpdateCateName(ctx context.Context, orgId, assetCateId, cateName string) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": assetCateId, "orgId": orgId}, bson.M{"$set": bson.M{"cateName": cateName}})
	return err
}

func (db *_AssetCateDao) UpdateAssetCount(ctx context.Context, orgId, assetCateId string, count uint32) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": assetCateId, "orgId": orgId}, bson.M{"$set": bson.M{"assetCount": count}})
	return err
}
